#include "wokerThread.h"
#include "EventLoop.h"
#include <stdio.h>
//初始化
int workerThreadInit(struct WorkerThread* thread, int index)
{
    thread->evLoop = NULL;
    thread->threadID = 0;
    sprintf(thread->name, "SubThread-%d", index);
    pthread_mutex_init(&thread->mutex, NULL);
    pthread_cond_init(&thread->cond, NULL);
    return 0; 
}

//子线程的回调函数
void* subThreadRunning(void* arg)
{
    struct WorkerThread* thread = (struct WorkerThread*)arg;
    //上锁
    pthread_mutex_lock(&thread->mutex);
    thread->evLoop = eventLoopInitEx(thread->name);
    pthread_mutex_unlock(&thread->mutex);
    //唤醒主线程
    pthread_cond_signal(&thread->cond);
    eventLoopRun(thread->evLoop);
    return NULL;
}
    
//启动线程
void workerThreadRun(struct WorkerThread* thread)
{
    //创建子线程
    pthread_create(&thread->threadID, NULL, subThreadRunning, thread);
    //阻塞主线程，让当前函数不会结束，等待创建的子线程完成evLoop的初始化
    //防止主线程对未完成初始化的evLoop进行操作
    pthread_mutex_lock(&thread->mutex);
    while(thread->evLoop == NULL)
    {
        pthread_cond_wait(&thread->cond, &thread->mutex);
    }
    pthread_mutex_unlock(&thread->mutex);
}